//index.js
//获取应用实例
var app = getApp()
//var WxParse = require('../../../wxParse/wxParse.js');
var timer;
var chima_select = '';

Page({
  data: {
    images: {},
    bannerImages: {
      width: 750,
      height: 750,
      sell_price: 0,
      promotion: { price: 0 }
    },
    imgurl2: app.urlimg,
    goods_id: '',
    product_id: 0,
    good_num: 1,
    price: null,
    regiment_model: true,
    userInfo: {},
    isAnimation2: false,
    isAnimation1: false,
    isScroll: true,
    selectItem: {},
    actionType: 'cart',
    //  购物数量被选择后改背景色
    isAddNumber: false,
    isReduceNumber: false,
    loadHidden: false,
    loadText: "加载中...",
    goods_thumb: '',
    isScrollTop: true,
    regiment_userid: 0,//开团id
    regiment_share_userid: 0,//
    data2: {
      pintuan: 0,
    },
    content_photo: {},
    defaultpages: 2,
    store_nums: 0,
    /** 快捷按钮 **/
    look_navigation: true,
    hint: true,//客服提示
    shortcut: false,
    shor_box: [
      { name: '首页', img: '/pages/icon/home1.png' },
      { name: '足迹', img: '/pages/icon/map1.png' },
      { name: '搜索', img: '/pages/icon/search1.png' },
      { name: '购物车', img: '/pages/icon/cart1.png' },
    ],
    select_box: false,
    cascading: 0,
    all_select: 0,//购物车全选
    money: '0.00',//结算总价格
    money_save: '0.00',//节约金额
    list_box: [],

    /***评论 */
    comment_box: [],

    // 承诺保证
    promise: [
      { img: '/pages/icon/353145762604299082.png', text: '正品保证' },
      // { img: '/pages/icon/huodaofuk.png', text: '货到付款' },
      { img: '/pages/icon/guo.png', text: '双倍果果币' },
      { img: '/pages/icon/7tian.png', text: '七天无理由退换' },
      // { img: '/pages/icon/maigui.png', text: '买贵必赔' },
    ],
    service_description: true,
    //优惠劵
    coupon: [],
    //判断下拉加载
    go_look: true,
    group_user: [],
    // 模态框
    model: false,
    // 保存全部团组的剩余时间
    time_box: [],
    regiment_id: 0,
    groupType: 0,
    verify: false,
    go_num: false,
    banner_index: 0,//默认加载
    sold_out: true,//当产品售空时
    //骆驼卡
    camel_card: false,
  },

  // 开团查看更多
  check_more: function () {
    this.setData({
      model: true,
    })
  },
  /*关闭显示正在开团的人 */
  check_delete: function () {
    this.setData({
      model: false,
    })
  },
  /**去参团 */
  tuxedo: function (e) {
    var order_id = e.currentTarget.dataset.id;
    var goods_id = e.currentTarget.dataset.goodsid;
    wx.navigateTo({
      url: '../../group/group_of/group_of?order_id=' + order_id + '&id=' + goods_id,
    })
  },

  onLoad: function (o) {
    chima_select = '';
    var regiment_userid = typeof (o.regiment_userid) == 'undefined' ? 0 : o.regiment_userid
    var regiment_share_userid = typeof (o.regiment_share_userid) == 'undefined' ? 0 : o.regiment_share_userid
    //团长id
    if (regiment_userid !== 0) {
      wx.setStorage({
        key: "regiment_userid",
        data: regiment_userid
      })

      wx.setStorage({
        key: "share_goods_id",
        data: o.id
      })

    }
    //分享者id
    if (regiment_share_userid !== 0) {
      wx.setStorage({
        key: "regiment_share_userid",
        data: regiment_share_userid
      })
    }
		/**
			* author: weiki
			* 添加一个group_type 判断拼团类型
			*/
    if (typeof (o.group_type) != 'undefined') {
      this.data.groupType = o.group_type;
    }

    if (typeof (o.verify) != 'undefined') {
      this.data.verify = o.verify;
    }

    var that = this;
    //判断用户进入商品详情页的次数（用于控制客服提示的次数）
    var value = '';
    wx.getStorage({
      key: 'entrance',
      success: function (res) {
        value = res.data;
        ++value;
        if (value > 5) {
          that.setData({
            hint: false,
          })
        }
        wx.setStorage({
          key: "entrance",
          data: value
        })
      }
    })


    wx.getSystemInfo({
      success: function (res) {
        var h = res.screenHeight,
          h = h + 'px';
        that.setData({
          goods_id: o.id,
          screenHeight: h,
          entrance: value,//判断用户进入商品详情页的次数（用于控制客服提示的次数）
        })
      }
    })


    // app.getUserInfo(function (token_key) {
    var tg = typeof (o.tg) == 'undefined' ? 0 : o.tg
    var regiment_userid = typeof (wx.getStorageSync('regiment_userid')) == 'undefined' ? 0 : wx.getStorageSync('regiment_userid')
    var regiment_share_userid = typeof (wx.getStorageSync('regiment_share_userid')) == 'undefined' ? 0 : wx.getStorageSync('regiment_share_userid')



    app.app_load(load_fn);//用户登录
    function load_fn() {
      //获取数据
      wx.request({
        url: app.url + 'api_goods/goods_detailV1',
        data: {
          id: o.id,
          // id:1208,
          tg: tg,
          regiment_share_userid: regiment_share_userid,
          regiment_userid: regiment_userid,
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key'),
        }, success: function (json) {
          if (json.data.done == true) {

            wx.setStorage({
              key: "regiment_userid",
              data: json.data.result.promotion.regiment_userid
            })

            wx.setStorage({
              key: "regiment_share_userid",
              data: json.data.result.promotion.regiment_share_userid
            })
            wx.setNavigationBarTitle({
              title: json.data.result.name,
            })

            //拼团  抽奖团的判断跳转
            if (json.data.result.promotion != '' && ((json.data.result.promotion.group_type == 2 || json.data.result.promotion.group_type == 3) || json.data.result.promotion.group_type == 1) && json.data.result.promotion.is_expire != 3) {
              console.log("----------------------------------------------------------跳转到拼团  抽奖团的详情页");
              wx.redirectTo({
                url: '/pages/group/groupdetail/index?id=' + json.data.result.id + "&regiment_id=" + json.data.result.promotion.id + "&group_type=" + json.data.result.promotion.group_type,
              })
            }

            //显示抢购时判断商品是否已售罄（已售罄）
            var sold_out = true;
            if (json.data.result.store_nums == 0) {
              sold_out = false;
            }

            //判断颜色所对应的尺码是否全部为0，是的话就去除，否则显示
            var spec_array_all = json.data.result.spec_array;//获取尺码和颜色的规格
            var spec_detail_all = json.data.result.spec_detail;//获取所有尺码的价格和库存数量

            var genre_one = '';
            if (spec_array_all[0] != undefined) {
              genre_one = spec_array_all[0].py;
            }
            var genre_two = '';
            if (spec_array_all[1] != undefined) {
              genre_two = spec_array_all[1].py;
            }

            var spec_detail_all_num_all = [];//保存全部款式商品所对应的数量
            var spec_detail_all_num = [];//保存数量为0的各种款式商品
            for (var i in spec_detail_all) {
              var name = spec_detail_all[i].spec.substr(genre_one.length, spec_detail_all[i].spec.indexOf(genre_two) - genre_two.length);
              // 保存全部商品所对应的数量
              if (spec_detail_all_num_all.length == 0) {
                spec_detail_all_num_all.push({ name: name, num: 0 });
              }
              for (var k in spec_detail_all_num_all) {
                if (spec_detail_all_num_all[k].name == name) {
                  var num = spec_detail_all_num_all[k].num;
                  spec_detail_all_num_all[k].num = ++num;
                } else {
                  ++k;
                  if (spec_detail_all_num_all[k] == undefined) {
                    spec_detail_all_num_all.push({ name: name, num: 1 });
                  }
                }
              }

              // 保存数量为0的款式商品
              if (spec_detail_all[i].store_nums == 0) {
                if (spec_detail_all_num[name] == undefined) {
                  spec_detail_all_num[name] = 1;
                } else {
                  spec_detail_all_num[name]++;
                }
              }
            }


            // 去除全部尺码为0的款式
            for (var r in spec_detail_all_num_all) {
              if (spec_detail_all_num_all[r].num == spec_detail_all_num[spec_detail_all_num_all[r].name]) {
                for (var o in spec_array_all[0].value) {
                  if (spec_array_all[0].value[o].value == spec_detail_all_num_all[r].name) {
                    json.data.result.spec_array[0].value.splice(o, 1);
                  }
                }
              }
            }


            var num_all_box = json.data.result.spec_array;//获取尺码和颜色的规格

            var spec_title = ''
            if (!num_all_box.length > 0) {
              spec_title = '默认属性'
            } else {
              for (var i = 0; i < num_all_box.length; i++) {
                if ((num_all_box.length - 1) == i) {
                  spec_title += num_all_box[i].name
                } else {
                  spec_title += num_all_box[i].name + '|'
                }
              }
            }

            json.data.result.spec_title = spec_title;
            json.data.result.sell_price = json.data.result.promotion.length > 0 ? '' : '￥' + json.data.result.sell_price;
            //判断是否有空置的图片
            for (var i = 0; i < json.data.result.goods_comment.comment_list.length; i++) {
              var list_img = [];
              for (var g = 0; g < json.data.result.goods_comment.comment_list[i].comment_img.length; g++) {
                if (json.data.result.goods_comment.comment_list[i].comment_img[g] != '') {
                  list_img.push(json.data.result.goods_comment.comment_list[i].comment_img[g])
                }
              }
              json.data.result.goods_comment.comment_list[i].comment_img = list_img;
            }



            // 判断评论集合的数量
            var statistics = json.data.result.goods_comment.statistics;
            //数组移除指定对象或下标i
            var all_silts = [];
            for (var i = 0; i < statistics.length; i++) {
              if (parseInt(statistics[i].number) != parseInt(0)) {
                all_silts.push(statistics[i]);
              }
            }
            json.data.result.goods_comment.statistics = all_silts;



            var timestamp = parseInt(new Date().getTime() / 1000);

            var imgarr = imageForeach(json.data.result.photo, 1);//默认取一张
            that.setData({
              data: json.data.result,
              data_Back: json.data.result,//获取副本
              store_nums: json.data.result.store_nums,
              loadHidden: true,
              comment: (json.data.result.data != undefined ? json.data.result.data : ''),
              content_photo: json.data.result.content,
              // time_num: time_num,
              timestamp: timestamp,
              imgurl: imgarr.imgurl,
              goods_thumb: imgarr.goods_thumb,
              banner_index: 0,
              // statistics_lists: statistics_lists,
              sold_out: sold_out,
              // camel_card: true,

            })

            countdown(that)

          } else if (json.data.message == "商品不存在") {
            wx.redirectTo({
              url: '/pages/index/null/index',
            })
          } else {
            //失败
            app.apperror(json)
          }

        }, complete: function () {

        }
      })

      //获取优惠券
      that.getCouponList();
    }
  },
  contactTap: function (e) {
    wx.redirectTo({
      url: e.detail.path + '?id=' + e.detail.query.id
    })
  },
  remain_time: function (Timegg, index) {
    var that = this;
    Timegg -= 1000;

    var day = parseInt(Timegg / 100 / 60 / 60 / 24, 10);
    if (('' + day).length == 1) {
      day = '0' + day;
    }

    var hours = parseInt(Timegg / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 
    if (('' + hours).length == 1) {
      hours = '0' + hours;
    }
    var minutes = parseInt(Timegg / 1000 / 60 % 60, 10);//计算剩余的分钟 
    if (('' + minutes).length == 1) {
      minutes = '0' + minutes;
    }
    var seconds = parseInt(Timegg / 1000 % 60, 10);//计算剩余的秒数 
    if (('' + seconds).length == 1) {
      seconds = '0' + seconds;
    }
    var times = hours + ":" + minutes + ":" + seconds;//排列时间

    var group_user = that.data.group_user;//获取开团数量
    var time_box = that.data.time_box;//获取每个团的毫秒数
    group_user[index].remain_time = times;//将转化的标准时间放入每个团中
    time_box[index] = Timegg;//将每个团的毫秒数（减去一秒后）的毫秒数储存下来

    that.setData({
      group_user: group_user,
      time_box: time_box,
    })

  },
  // 服务说明
  privilege: function () {
    var that = this;
    var shortcut = that.data.shortcut;
    shortcut = !shortcut;
    that.setData({
      shortcut: shortcut,
      service_description: false,
      look_navigation: false,
    })
  },
  privilege_dele: function () {
    var that = this;
    that.setData({
      shortcut: !that.data.shortcut,
      service_description: true,
      look_navigation: true,
    })
  },
  //领取优惠劵
  pick: function (e) {
    var couponId = e.currentTarget.dataset.id;
    var that = this;
    var index = e.currentTarget.dataset.index;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    wx.request({
      url: app.url + "?controller=api_coupon&action=receive",
      data: {
        couponId: couponId
      },
      header: {
        'content-type': 'application/json', // 默认值
        'token': wx.getStorageSync('token_key')
      },
      success: function (res) {
        wx.hideLoading();
        console.log(res);
        var coupon = that.data.coupon;
        if (res.data.result) {
          if (coupon[index].restricts != 0) {
            coupon[index].restricts--;
            wx.showToast({
              title: '优惠劵领取成功',
              icon: 'success',
              duration: 500,
              mask: true,
            })
            that.setData({
              coupon: coupon
            })
          } else {
            wx.showToast({
              title: '您已经领取完了哦~',
              icon: 'loading',
              duration: 500,
              mask: true,
            })
          }
        }
      }
    })
  },


  onReady: function () {
    this.shortcut_animation00 = wx.createAnimation();
    this.shortcut_animation01 = wx.createAnimation();
    this.shortcut_animation02 = wx.createAnimation();
    this.shortcut_animation03 = wx.createAnimation();
    this.preview_animation = wx.createAnimation();
    this.scrollTop_animation = wx.createAnimation();
    this.settlement_animation = wx.createAnimation();
    //客服提示
    var that = this;
    setTimeout(function () {
      that.setData({
        hint: false,
      })
    }, 5000)


  },
  //商品连接
  goodslink: function (e) {
    var fid = e.currentTarget.id
    wx.redirectTo({
      url: '/pages/index/detail/index?id=' + fid,
    })
  },
  /*********************** 评论 **********/
  discuss: function (e) {
    var id = e.currentTarget.id;
    var label_id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.hi;
    wx: wx.navigateTo({
      url: '/pages/index/detail/discuss/index?goods_id=' + id + '&type=' + type + '&label_id=' + label_id,
    })
  },
  // 查看图片
  previewImage: function (e) {
    var that = this;
    //获取当前图片的下表
    var num = e.currentTarget.dataset.index;//获取评论的下标
    var indexs = e.currentTarget.dataset.indexs;//获取评论图片的下标
    //数据源
    var comment_img = that.data.data.goods_comment.comment_list[num].comment_img;//获取被点击的评论图片数组
    var bun = [];
    for (var i = 0; i < comment_img.length; i++) {
      var all = that.data.imgurl2 + comment_img[i];
      bun.push(all)
    }
    wx.previewImage({
      //当前显示下表
      current: bun[indexs],
      //数据源
      urls: bun,
    })
  },




  onReachBottom: function () {
    /* this.setData({ content_photo: this.data.data.content })*/
    var that = this;
    if (that.data.go_look) {
      that.setData({
        go_look: false,
      })
      that.setData({ loadHidden: true, loadText: that.data.loadText })
      var forumPage = that.data.defaultpages
      wx.request({
        url: app.url + 'api_goods/goods_detail_photoV1',
        data: {
          page: forumPage,
          id: that.data.goods_id
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        },
        success: function (res) {
          console.log(res.data);
          if (res.data.done == true) {
            console.log('加载~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
            //var newData = that.data.data.content .concat(res.data.result.content);
            var newData = res.data.result.content;
            that.setData({
              defaultpages: ++that.data.defaultpages,
              content_photo: newData,
              loadHidden: true,
              go_look: true,
            })
          } else {
            //提示信息
            wx.showToast({
              title: '已经到最底了',
              icon: 'loading',
              duration: 1100,
            })
            that.setData({ loadHidden: true, loadText: '已经到最底了', go_look: true, });
          }
        }, complete: function () {
          wx.hideNavigationBarLoading() //完成停止加载
          wx.stopPullDownRefresh() //停止下拉刷新
        }
      })

    }


  },
  onHide: function () {
    clearTimeout(timer);
  },
  onUnload: function () {
    clearTimeout(timer);
  },
  regiment_desc: function () {
    this.setData({
      regiment_model: false,
    })
  },
  modalOk: function () {
    this.setData({
      regiment_model: true,
    })
  },
  onShow: function () {
    //加拼团
    var that = this;
    var group_user = that.data.group_user;
    var time_box = that.data.time_box;
    if (group_user != '') {
      timess = setInterval(function () {
        for (var i = 0; i < that.data.group_user.length; i++) {
          that.remain_time(that.data.time_box[i], i);
        }
      }, 1000);
    }
    // 遍历图片数组
    if (this.data.data == null) return;
    // 秒杀代码
    countdown(this);

  },

  //  响应选择颜色和尺寸
  selectTAP: function () {
    this.setData({
      isAnimation2: true,
    })

    var animation = wx.createAnimation({
      duration: 2000,
      timingFunction: 'ease-in-out'
    })

    this.animation = animation
    var h = "245rpx";
    animation.height(h).translateY(-h).step();
    this.setData({
      animationData: animation.export()
    })
  },
  // 悬浮被单击
  xuanfuTAP: function () {
    var that = this;
    that.setData({
      isAnimation2: false,
      isAnimation1: false,
    })
  },
  manjian: function () {
    this.setData({
      isAnimation1: true
    })
  },
  imageLoad: function (e) {
    var $width = e.detail.width,    //获取图片真实宽度
      $height = e.detail.height,
      ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = 718,           //设置图片显示宽度，左右留有16rpx边距
      viewHeight = 718 / ratio;    //计算的高度值
    var image = this.data.images;
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    image[e.target.dataset.index] = {
      width: viewWidth,
      height: viewHeight
    }
    this.setData({
      images: image
    })
  },
  bannerImagesLoad: function (e) {
    var that = this
    var $width = e.detail.width,    //获取图片真实宽度
      $height = e.detail.height,
      ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = 750,           //设置图片显示宽度，左右留有16rpx边距
      viewHeight = 750 / ratio;    //计算的高度值
    var image = this.data.bannerImages;
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    image[e.target.dataset.index] = {
      width: viewWidth,
      height: viewWidth
    }
    //加载完再加载一张
    var imgarr = imageForeach(that.data.data.photo, that.data.banner_index + 2)
    var aa = that.data.banner_index + 1
    that.setData({
      banner_index: that.data.banner_index + 1,
      Bannerimages: image,
      imgurl: imgarr.imgurl,
      goods_thumb: imgarr.goods_thumb,
    })
  },
  //返回首页
  homeTAP: function () {
    wx.reLaunch(
      {
        url: '/pages/index/index',
        success: function (res) {
          clearTimeout(timer);
        }
      }
    )

  },
  //  响应加入购物车
  shopTAP: function (e) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    that.setData({
      isAnimation2: true,
      actionType: 'cart',
      shopping_status: 0,
    })
    wx.hideLoading();

    // 调用动画方法
    moveAnimation(that);
  },

  // 立即购买中的  加入购物车
  shopTAP_click: function () {
    this.setData({
      actionType: 'cart'
    })
    this.nextStep();
  },


  favorite: function (e) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    wx.request({
      url: app.url + 'api_goods/favorite_add',
      data: {
        goods_id: that.data.goods_id,
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },
      success: function (res) {
        wx.hideLoading();
        that.data.data.is_favorite = res.data.result.favorite ? '1' : '0';
        that.setData({ 'data': that.data.data, });
        var text = '';
        if (res.data.result.favorite) {
          text = '收藏成功';
        } else {
          text = '取消收藏';
        }
        wx.showToast({
          title: text,
          icon: 'success',
          duration: 1200,
        })
      }
    })
  },
  specTAP: function (e) {
    var that = this;
    //获取副本
    var data_Back = that.data.data_Back;
    if (that.data.data.spec_array[1]) {
      for (var i = 0; i < that.data.data.spec_array[1].value.length; i++) {
        if (that.data.data.spec_array[1].value[i].select == 1) {
          chima_select = that.data.data.spec_array[1].value[i].value;
        }
      }
    }
    if (e.currentTarget.dataset.py == "yanse") {
      if (data_Back.spec_array[1]) {
        for (var i = 0; i < data_Back.spec_array[1].value.length; i++) {
          data_Back.spec_array[1].value[i].select = 0;
        }
      }
      that.setData({
        data: data_Back,
      })
    }

    var py = e.currentTarget.dataset.py;//获取点击的标题
    var spec_array = that.data.data.spec_array;//获取所有样式
    var value = e.currentTarget.dataset.value;//获取选择的颜色
    var spec_detail = that.data.data.spec_detail;//获取所有尺码
    var product_name = [];
    var gobuy = true
    for (var i = 0; i < spec_array.length; i++)//判断选择的样式(颜色或尺码)以及更改显示图片
    {
      if (spec_array[i].py == py) {
        spec_array[i].select = 1;
        that.data.data_Back.spec_array[i].select = 1;
      }
      for (var n = 0; n < spec_array[i].value.length; n++) {
        if (spec_array[i].value[n].value == value) {
          if (typeof (spec_array[i].value[n].img) != 'undefined' && spec_array[i].value[n].img.length > 2) {
            that.setData({ goods_thumb: that.data.imgurl2 + spec_array[i].value[n].img })//更改显示图片


            if (e.currentTarget.dataset.py == "yanse" && spec_array[1] != undefined) {
              var spec_name = [];//获取有存货的商品
              // 点击判断是否有存货
              var size = spec_array[1].value;
              var arr = [];
              //获取用户选择的样式
              for (var g = 0; g < size.length; g++) {
                arr.push("yanse" + value + "chima" + size[g].value)
              }

              for (var h = 0; h < spec_detail.length; h++) {
                for (var yy = 0; yy < arr.length; yy++) {
                  if (spec_detail[h].spec == arr[yy] && spec_detail[h].store_nums != 0) {
                    product_name.push(spec_detail[h]);
                  }
                }
              }

              //获取字符串的函数
              function getStr(string, str) {
                var str_before = string.split(str)[0];
                var str_after = string.split(str)[1];
                return str_after;
              };

              for (var tt = 0; tt < product_name.length; tt++) {
                // var num = product_name[tt].spec.replace(/[^0-9]/ig, "");

                var num = getStr(product_name[tt].spec, 'chima');

                var all = that.data.data_Back.spec_array[1].value;
                var names = '';
                for (var kk = 0; kk < all.length; kk++) {
                  if (all[kk].value == num) {
                    names = all[kk].name;
                  }
                }

                spec_name[tt] = { name: names, img: '', value: num, select: 0 };
                if (spec_name[tt].value == chima_select) {
                  spec_name[tt].select = 1;
                }
              }
              that.setData({ 'data.spec_array[1].value': spec_name, })
            }
          }
          spec_array[i].value[n].select = 1;
          that.data.data_Back.spec_array[i].value[n].select = 1;
        } else {
          if (spec_array[i].py == py) {
            spec_array[i].value[n].select = 0;
            that.data.data_Back.spec_array[i].value[n].select = 0;
          }
        }
      }
      spec_array[i].value
    }

    var selectItem = '';//拼接选取的样式
    for (var i = 0; i < spec_array.length; i++) {
      if (!spec_array[i].select) {
        gobuy = false
      } else {
        selectItem += spec_array[i].py
      }
      for (var n = 0; n < spec_array[i].value.length; n++) {
        if (spec_array[i].value[n].select == 1) {
          selectItem += spec_array[i].value[n].value
        }
      }
    }

    var goods_num = 0;
    for (var i = 0; i < that.data.data.spec_detail.length; i++) {//计算数量
      if (that.data.data.spec_detail[i].spec.substring(0, selectItem.length) == selectItem) {
        goods_num += parseInt(that.data.data.spec_detail[i].store_nums);
      }
    }
    that.data.data.store_nums = goods_num;


    if (gobuy) {
      var newdata = that.data.data
      var product_id = 0//初始时，设置产品编号为0
      for (var i = 0; i < spec_detail.length; i++) {
        if (spec_detail[i].spec == selectItem) {
          if (typeof (newdata.promotion.price) == 'undefined') {
            newdata.sell_price = spec_detail[i].sell_price;
          }
          newdata.store_nums = spec_detail[i].store_nums//产品数量
          product_id = spec_detail[i].product_id//产品编号
        }
      }
      that.setData({
        product_id: product_id,
        data: newdata
      })

    }


    that.data.data.spec_array = spec_array//替换显示
    that.setData({
      data: that.data.data,
    })

    if (that.data.data.activity == undefined && that.data.data.promotion == '') {

      that.setData({
        'data.activity.end_time': 1,
      })
    }

  }
  ,
  /***************************************** 快捷按钮 *******************************/
  shortcut_btn: function () {
    var that = this;
    if (that.data.cascading == 1) {
      that.close_track();
      that.setData({
        cascading: 0,
      })
    } else {
      var shortcut = that.data.shortcut;
      shortcut = !shortcut;
      if (shortcut == true) {
        this.shortcut_animation00.translateY('-9vh').opacity(1).step();
        this.shortcut_animation01.translateY('-18vh').opacity(1).step();
        this.shortcut_animation02.translateY('-27vh').opacity(1).step();
        this.shortcut_animation03.translateY('-36vh').opacity(1).step();
      } else {
        this.shortcut_animation00.translateY(0).opacity(0).step();
        this.shortcut_animation01.translateY(0).opacity(0).step();
        this.shortcut_animation02.translateY(0).opacity(0).step();
        this.shortcut_animation03.translateY(0).opacity(0).step();
      }

      that.setData({
        look_navigation: true,
        service_description: true,
        shortcut: shortcut,
        shortcut_animation00: that.shortcut_animation00.export(),
        shortcut_animation01: that.shortcut_animation01.export(),
        shortcut_animation02: that.shortcut_animation02.export(),
        shortcut_animation03: that.shortcut_animation03.export(),
      })
    }
  },
  amenity: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;

    //0为首页  1为足迹  2为搜索  3为购物车
    if (id == 0) {
      wx.redirectTo({
        url: '../index',
      })
    } else if (id == 1) {
      that.preview_animation.translateY(-400).step();
      //************************伪数据
      wx.request({
        url: app.url + 'api_footprint/footprint_group_list',
        data: {
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        }, success: function (json) {
          console.log(json.data.result)
          that.setData({
            element: true,
            cascading: 1,
            footprint: json.data.result,
          })
        }
      })
    } else if (id == 2) {
      this.shortcut_animation00.translateY(0).opacity(0).step();
      this.shortcut_animation01.translateY(0).opacity(0).step();
      this.shortcut_animation02.translateY(0).opacity(0).step();
      this.shortcut_animation03.translateY(0).opacity(0).step();

      that.setData({
        shortcut: false,
        shortcut_animation00: that.shortcut_animation00.export(),
        shortcut_animation01: that.shortcut_animation01.export(),
        shortcut_animation02: that.shortcut_animation02.export(),
        shortcut_animation03: that.shortcut_animation03.export(),
      })
      wx.navigateTo({
        url: '../../search/index',
      })
    } else if (id == 3) {//购物车
      wx.reLaunch(
        {
          url: '/pages/shop/index',
          success: function (res) {
            clearTimeout(timer);
          }
        })
    }

    that.setData({
      preview_animation: that.preview_animation.export(),
    })
  },
  //清空足迹
  clear_track: function () {
    var that = this
    wx.request({
      url: app.url + 'api_footprint/clear_footprint',
      data: {
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      }, success: function (json) {
        that.setData({
          footprint: null,
        })
      }
    })
  },
  //关闭足迹显示框或购物车框
  close_track: function () {
    var that = this;
    that.preview_animation.translateY(0).step();
    that.settlement_animation.translateY(0).step();
    that.shortcut_animation00.translateY(0).opacity(0).step();
    that.shortcut_animation01.translateY(0).opacity(0).step();
    that.shortcut_animation02.translateY(0).opacity(0).step();
    that.shortcut_animation03.translateY(0).opacity(0).step();

    that.setData({
      shortcut: false,
      cascading: 0,
      preview_animation: that.preview_animation.export(),
      settlement_animation: that.settlement_animation.export(),
      shortcut_animation00: that.shortcut_animation00.export(),
      shortcut_animation01: that.shortcut_animation01.export(),
      shortcut_animation02: that.shortcut_animation02.export(),
      shortcut_animation03: that.shortcut_animation03.export(),
    })
  },
  // 购物车操作
  //商品单选操作
  single_click: function (e) {
    var that = this;
    var shop_index = e.currentTarget.dataset.shop_index;
    var goods_id = e.currentTarget.dataset.goods_id;
    var cartlist = that.data.cartlist;
    var num = 0;
    var cartnum = 0;
    var all_select = 0;
    if (cartlist[shop_index].products[goods_id].select == 0) {
      cartlist[shop_index].products[goods_id].select = 1;
    } else {
      cartlist[shop_index].products[goods_id].select = 0;
    }
    for (var i = 0; i < cartlist[shop_index].products.length; i++) {
      if (cartlist[shop_index].products[i].select == 1) {
        ++num;
        ++cartnum;
      }
    }
    if (num == cartlist[shop_index].products.length) {
      cartlist[shop_index].select = 1;
      var shop_num = 0;
      for (var i = 0; i < cartlist.length; i++) {
        if (cartlist[i].select == 1) {
          ++shop_num;
        }
      }
      if (shop_num == cartlist.length) {
        all_select = 1;
      }
    } else {
      all_select = 0;
      cartlist[shop_index].select = 0;
    }
    that.setData({
      cartnum: cartnum,
      all_select: all_select,
      cartlist: cartlist,
    })
    that.settle();
  },
  //店铺全选操作
  store_click: function (e) {
    var that = this;
    var shop_index = e.currentTarget.dataset.shop_index;
    var cartlist = that.data.cartlist;
    var cartnum = 0;

    if (cartlist[shop_index].select == 0) {
      cartlist[shop_index].select = 1;
      all(1);
      cartnum = cartlist[0].products.length;
    } else {
      cartlist[shop_index].select = 0;
      cartnum = 0;
      all(0);
    }
    function all(gg) {
      for (var i = 0; i < cartlist[shop_index].products.length; i++) {
        if (!cartlist[shop_index].products[i].isAccount) {
          cartlist[shop_index].products[i].select = gg;
        }
      }
    }

    var all_select = 0;

    for (var i = 0; i < cartlist.length; i++) {
      if (cartlist[i].select == 1) {
        ++all_select;
      }
    }
    if (all_select == cartlist.length) {
      all_select = 1;
    } else {
      all_select = 0;
    }

    console.log(cartlist);
    that.setData({
      cartnum: cartnum,
      all_select: all_select,
      cartlist: cartlist,
    })
    that.settle();
  },
  //商品全选操作
  check_all: function () {
    var that = this;
    var all_select = that.data.all_select;
    var cartlist = that.data.cartlist;
    var cartnum = 0;

    if (all_select == 0) {
      all_select = 1;
      all(1);
      cartnum = cartlist[0].products.length;
    } else {
      all_select = 0;
      all(0);
      cartnum = 0;
    }

    function all(gg) {
      for (var i = 0; i < cartlist.length; i++) {
        cartlist[i].select = gg;
        for (var k = 0; k < cartlist[i].products.length; k++) {
          if (!cartlist[i].products[k].isAccount) {
            cartlist[i].products[k].select = gg;
          }
        }
      }
    }

    that.setData({
      cartnum: cartnum,
      all_select: all_select,
      cartlist: cartlist,
    })
    that.settle();
  },
  //领取优惠券
  pick_coupon: function () {
    wx.navigateTo({
      url: '/pages/account/discount/coupon/index',
    })
  },
  //结算
  settle: function () {
    var that = this;
    var cartlist = that.data.cartlist;
    var money = 0;
    var money_save = 0;

    for (var i = 0; i < cartlist.length; i++) {
      for (var k = 0; k < cartlist[i].products.length; k++) {
        if (cartlist[i].products[k].select == 1) {
          money += parseFloat(cartlist[i].products[k].price) * cartlist[i].products[k].number;
          money_save += parseFloat(cartlist[i].products[k].market_price) * cartlist[i].products[k].number;
        }
      }
    }

    // console.log(money.toFixed(2));
    // console.log(money_save.toFixed(2));
    money_save = money_save - money;

    that.setData({
      money: money.toFixed(2),
      money_save: money_save.toFixed(2),
    })
  },
  // 商品增加数量
  add_num: function (e) {
    var that = this;
    var shop_index = e.currentTarget.dataset.shop_index;
    var goods_id = e.currentTarget.dataset.goods_id;
    var cartlist = that.data.cartlist;


    var num = cartlist[shop_index].products[goods_id].number;
    var store_nums = cartlist[shop_index].products[goods_id].store_nums;
    if (num < store_nums) {
      cartlist[shop_index].products[goods_id].number = ++num;
      //到接口更新数量api_order/edit_cart_number?cart_id=5&number=5 

      wx.request({
        url: app.url + 'api_order/edit_cart_number',
        data: {
          'cart_id': cartlist[shop_index].products[goods_id].id,
          number: num
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        }, success: function (json) {

          if (!json.data.done) {
            cartlist[shop_index].products[goods_id].number--;
            that.setData({
              cartlist: cartlist,
            });
            wx.showModal({
              title: '提示',
              content: json.data.message,
            })
          }
          that.setData({
            cartlist: cartlist,
          })
          that.settle();

        }
      })
    } else {
      //提示信息
      wx.showToast({
        title: '已达最大库存',  //标题  
        icon: 'loading',
        duration: 1500,
      })
    }

  },
  // 商品减去数量
  dele_num: function (e) {
    var that = this;
    var shop_index = e.currentTarget.dataset.shop_index;
    var goods_id = e.currentTarget.dataset.goods_id;
    var cartlist = that.data.cartlist;

    var num = cartlist[shop_index].products[goods_id].number;
    if (num > 1) {
      cartlist[shop_index].products[goods_id].number = --num;

      wx.request({
        url: app.url + 'api_order/edit_cart_number',
        data: {
          'cart_id': cartlist[shop_index].products[goods_id].id,
          number: num
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        }, success: function (json) {
          that.setData({
            cartlist: cartlist,
          })
        }
      })
      that.settle();
    }
  },
  /*删除产品 */
  dele_goods: function (e) {
    var that = this;
    wx.showModal({
      title: '删除商品',
      content: '确定删除该商品吗？',
      success: function (res) {
        if (res.confirm) {
          var shop_index = e.currentTarget.dataset.shop_index;
          var cid = e.currentTarget.dataset.id;

          var goods_id = e.currentTarget.dataset.id;
          var cartlist = that.data.cartlist;


          wx.request({
            url: app.url + 'api_order/del_cart',
            data: {
              'cart_id': cid
            },
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token_key')
            }, success: function (json) {
              // 删除当前商品
              var products = cartlist[0].products
              var newpro = []
              var delmoney = 0

              for (var i = 0; i < products.length; i++) {
                if (products[i].id !== cid) {
                  newpro.push(products[i])
                } else {
                  delmoney = parseFloat(products[i].price * products[i].number)
                }
              }
              var money = parseFloat(that.data.money - delmoney);
              cartlist[0].products = newpro
              that.setData({
                cartlist: cartlist,
                money: money > 0 ? money.toFixed(2) : '0.00'
              })
            }
          })




        }
      }
    })
  },


  accounts_btn: function (e) {
    var that = this
    var cart_id = ''

    var products = that.data.cartlist[0].products

    for (var i = 0; i < products.length; i++) {
      if (products[i].select == 1) {
        cart_id += products[i].id + ','
      }
    }
    if (cart_id !== '') {
      var lastIndex = cart_id.lastIndexOf(',');
      if (lastIndex > -1) {
        cart_id = cart_id.substring(0, lastIndex);
      }
      wx.navigateTo({ url: '/pages/index/detail/orderDetail/index?actionType=cart&cart_id=' + cart_id })
    } else {
      wx.showModal({
        title: '提示',
        content: '您未选中商品~',
      })
    }


  },
  addNum: function (e) {
    var that = this;
    var good_num = that.data.good_num;//获取用户购买的数量
    var store_nums = that.data.data.store_nums;//获取库存
    if (good_num < store_nums) {
      that.setData({ good_num: good_num + 1 })
    } else {
      //提示信息
      wx.showToast({
        title: '产品数量大于库存',  //标题  
        image: '/pages/icon/delete.png',  //自定义图标的本地路径，image 的优先级高于 icon  
        duration: 1200,
      })
    }
  },
  cutNum: function (e) {
    if (this.data.good_num == 1) {
      return false
    }
    this.setData({ 'good_num': this.data.good_num - 1 })
  },
  // 响应评论
  commentTap: function (e) {
    wx.navigateTo({
      url: '/pages/account/showComment/index?goods_id=' + this.data.goods_id,
      success: function (e) {
      },
      fail: function (e) {
      }
    })

  },
  // 响应触摸增加加数量按钮改变背景色
  addTouchStart: function () {
    this.setData({
      isAddNumber: true,
    })
  },

  // 响应触摸结束增加加数量按钮改变背景色
  addTouchEnd: function () {
    this.setData({
      isAddNumber: false,
    })
  },

  // 响应触摸减少数量按钮改变背景色
  reduceTouchStart: function () {
    this.setData({
      isReduceNumber: true,
    })
  },

  // 响应触摸结束减少数量按钮改变背景色
  reduceTouchEnd: function () {
    this.setData({
      isReduceNumber: false,
    })
  },

  // 响应下一步
  nextStep: function () {
    var that = this;
    if (that.data.data.activity != undefined) {
      if (that.data.data.activity.start_time < that.data.timestamp && that.data.data.activity.end_time > that.data.timestamp) {
        that.setData({
          "data.sell_price": "￥" + that.data.data.activity.actPrice,
        })
      }
    }
    if (that.data.data.store_nums == 0) {
      wx.showModal({
        title: '提示',
        content: '商品库存不足！',
      })
      return
    }
    if (this.data.goods_id !== '' && this.data.good_num > 0) {
      //如果是点购买的
      if (this.data.actionType == 'buy') {

        wx.request({
          url: app.url + 'api_order/orderDisplay',
          data: {
            goods_id: this.data.goods_id,
            product_id: this.data.product_id,
            number: this.data.good_num,
            pintuan: this.data.data2.pintuan,
            regiment_id: this.data.data2.regiment_id,
            group_type: this.data.data2.group_type
          },
          header: {
            'content-type': 'application/json',
            'token': wx.getStorageSync('token_key')

          }, success: function (json) {
            if (json.data.done) {
              wx.navigateTo({
                url: '/pages/index/detail/orderDetail/index?goods_id=' + that.data.goods_id +
                '&product_id=' + that.data.product_id + '&number=' + that.data.good_num + '&actionType=buy',
                success: function (res) {
                  that.setData({
                    isAnimation2: false,
                  })
                }
              })
            } else {
              app.apperror(json);
            }

          }
        })
      } else {
        //如果是点加入购物的  api_order/add_cart?goods_id=384&product_id=5033&number=1 
        var that = this;
        wx.request({
          url: app.url + 'api_order/cart',
          data: {
          },
          header: {
            'content-type': 'application/json',
            'token': wx.getStorageSync('token_key')
          }, success: function (json) {
            if (json.data.done == true) {
              var cartlist = json.data.result;//获取购物车列表的商品
              var goods_id = that.data.data.id;//商品id
              var select_goods_num = that.data.good_num;//商品的数量
              var stock_goods_num = that.data.data.store_nums;//商品库存的总数量

              var cartlist_num = 0;
              var primary_further = 0;
              if (cartlist != '') {
                for (var i = 0; i < cartlist.length; i++) {
                  if (cartlist[i].goods_id == goods_id && primary_further == 0) {//判断是否有相同的商品在购物车
                    // if (cartlist[i].goods_id == goods_id) {//判断是否有相同的商品在购物车
                    primary_further++;

                    var color_size_select = [];//获取用户当前选中的颜色  以及  选中的尺码
                    color_size_select = harvest();


                    if (color_size_select[0] && color_size_select[1]) {//如果购物车里没有当前选择的 样式和尺码 时[true,true]
                      add_to();
                    } else if (color_size_select[0] && !color_size_select[1]) {//如果购物车里 有当前选择的样式 但 没有当前选中的尺码 时[true,false]
                      add_to();
                    } else if (!color_size_select[0] && color_size_select[1]) {//如果购物车里 没当前选择的样式 但 有当前选中的尺码 时[false,true]
                      add_to();
                    } else {//如果购物车里 既有当前选择的样式 也有当前选中的尺码 时[false,false]
                      var one = 0, two = 0;
                      if (that.data.data.spec_array[1] != undefined) {
                        for (var u in that.data.data.spec_array[1].value) {
                          if (that.data.data.spec_array[1].value[u].select == 1) {
                            one = that.data.data.spec_array[1].value[u].value
                          }
                        }
                      }
                      for (var l in cartlist) {
                        if (cartlist[l].product[1] != undefined && cartlist[l].product[1].value == one) {
                          two = l;
                        }
                      }

                      if ((parseInt(cartlist[two].number) + parseInt(select_goods_num)) > stock_goods_num) {
                        wx.showModal({
                          title: '提示',
                          content: '添加失败，您所加入购物车的商品超过库存数量！请重新选择',
                        })
                      } else {
                        ++cartlist_num;
                        if (cartlist_num == cartlist.length) {
                          add_to();
                        }
                      }
                    }


                    //判断用户当前选择的 款式和尺码 是否在购物车里已经存在
                    function harvest() {
                      var aaa = '';//获取用户当前选择的款式
                      var bbb = 0;//判断用户当前选择的 款式 是否存在在购物车
                      var ccc = [];
                      var ggg = false;//判断用户当前选择的 尺码 是否存在在购物车
                      var primary = 0;
                      for (var i in that.data.data.spec_array[0].value) {
                        if (that.data.data.spec_array[0].value[i].select == 1) {
                          aaa = that.data.data.spec_array[0].value[i].name;
                        }
                      }
                      var product_size_all = [];
                      for (var k in cartlist) {
                        if (cartlist[k].product[0].value != aaa) {
                          ++bbb;
                        }
                        if (cartlist[k].product[0].value == aaa) {
                          if (cartlist[k].product[1] != undefined) {
                            product_size_all.push(cartlist[k].product[1].value);
                          }
                        }
                      }

                      var user_elset_size = '';
                      if (cartlist[k].product[1] != undefined) {
                        for (var i in that.data.data.spec_array[1].value) {
                          if (that.data.data.spec_array[1].value[i].select == 1) {
                            user_elset_size = that.data.data.spec_array[1].value[i].value;
                          }
                        }
                      }

                      for (var kk in product_size_all) {
                        if (primary == 0) {
                          if (product_size_all[kk] == user_elset_size) {
                            ++primary;
                            ggg = false;
                          } else {
                            ggg = true;
                          }
                        }
                      }
                      ccc[0] = (bbb == cartlist.length);
                      ccc[1] = ggg;
                      return ccc;//false有相同的参数
                    }
                  } else {//当购物车里没有当前商品的id时
                    ++cartlist_num;
                    if (cartlist_num == cartlist.length) {
                      add_to();
                    }
                  }
                }
              } else {//当购物车为空时，成功添加
                add_to();
              }
            } else {
              app.apperror(json);
            }
          }
        })


        function add_to() {
          wx.request({
            url: app.url + 'api_order/add_cart',
            data: {
              goods_id: that.data.goods_id,
              product_id: that.data.product_id,
              number: that.data.good_num
            },
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token_key')
            }, success: function (json) {
              if (json.data.done) {
                that.data.data.cart_number = parseInt(that.data.data.cart_number) + parseInt(that.data.good_num);
                wx.showToast({
                  title: '添加购物车成功~',
                  icon: 'success',
                  duration: 2000
                })
                that.setData({
                  isAnimation2: false,
                  data: that.data.data
                })
              } else {
                wx.showModal({
                  title: '提示',
                  content: json.data.message,
                })
              }

            }
          })
        }





      }
    } else {
      wx.showModal({
        title: '提示',
        content: '参数不正常',
      })
    }

  },
  //响应即将开抢
  the_buyTAP: function () {
    wx.showModal({
      title: '提示',
      content: '该商品即将开抢，请耐心等候···',
    })
  },
  buyTAP_null: function () {
    wx.showModal({
      title: '提示',
      content: '抱歉，该商品已售罄',
    })
  },
  // 响应立即购买
  buyTAP: function (e) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    that.setData({
      isAnimation2: true,
      actionType: 'buy',
      data2: { pintuan: 0 },
      shopping_status: e.currentTarget.dataset.id,
    })
    wx.setStorage({
      key: "pintuan",
      data: '0'
    })

    wx.hideLoading();
    //  调用动画方法
    moveAnimation(that);

  },
  pintuan: function (e) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    wx.hideLoading();
    if (that.data.verify == false && (that.data.groupType == 3 || that.data.groupType == 4)) {
      var goodsId = that.data.goods_id;
      var regiment_id = that.data.regiment_id;
      wx.navigateTo({
        url: '/pages/group/verify/index?id=' + goodsId + '&regiment_id=' + regiment_id + '&group_type=' + that.data.groupType,
      });
    } else {
      that.setData({
        isAnimation2: true,
        actionType: 'buy',
        data2: { pintuan: 1, regiment_id: that.data.regiment_id, group_type: that.data.groupType },

      })
      wx.setStorage({
        key: "pintuan",
        data: '1'
      })
      //  调用动画方法
      moveAnimation(that);
    }
  },




  // 展示图片被单击
  imageTAP: function (e) {
    var current = e.currentTarget.id;
    wx.previewImage({
      current: current, // 当前显示图片的链接，不填则默认为 urls 的第一张
      urls: this.data.imgurl,
    })
  },
  goods_thumb: function (e) {
    var src = e.target.dataset.src
    if (src.indexOf("200_200_") != -1) {
      src = src.replace('200_200_', '640_640_');
    }
    var imgarr = [src]
    wx.previewImage({
      current: src, // 当前显示图片的链接，不填则默认为 urls 的第一张
      urls: imgarr,
    })

  }, goods_imgdetail: function (e) {
    var that = this
    var src = e.target.dataset.src
    var url = e.target.dataset.url
    if (url !== '') {
      wx.redirectTo({ url: url })

    } else {

      var imgarr = []
      for (var i = 0; i < that.data.content_photo.length; i++) {
        imgarr.push(that.data.imgurl2 + that.data.content_photo[i].src)

      }
      wx.previewImage({
        current: src, // 当前显示图片的链接，不填则默认为 urls 的第一张
        urls: imgarr,
      })
    }

  },
  swiperItem: function (e) {
    var that = this
    var cartlist = that.data.cartlist;


    if (cartlist[0].products[goods_id].select == 1) {
      cartlist[0].products[goods_id].select = 1;
    }


  },
  cart: function () {
    var that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    that.setData({
      shortcut: true,
    })
    var aaa = "-10vh";
    that.preview_animation.translateY(-400).step();
    that.settlement_animation.translateY(aaa).step();
    var selectImgs = [];
    var edits = [];
    wx.request({
      url: app.url + 'api_order/cart',
      data: {
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      }, success: function (json) {
        wx.hideLoading();
        if (json.data.done == true) {
          // var money=0 money:money,
          for (var i = 0; i < json.data.result.length; i++) {
            json.data.result[i].select = 0;
            json.data.result[i].isAccount = false;
            json.data.result[i].isAccount_title = '';
            //判断商品失效
            if (parseInt(json.data.result[i].store_nums) == 0 || parseInt(json.data.result[i].store_nums) < parseInt(json.data.result[i].number)) {
              json.data.result[i].isAccount = true;
              json.data.result[i].isAccount_title = '商品库存不足';
            } else if (parseInt(json.data.result[i].is_del) != 0) {
              json.data.result[i].isAccount = true;
              json.data.result[i].isAccount_title = '宝贝已不能购买，请联系店长';
            }
          }
          that.setData({
            settlement_animation: that.settlement_animation.export(),
            element: false,
            cascading: 1,
            cartnum: 0,
            cartlist: [{ store: "骆驼官方商城", select: 0, products: json.data.result },],
            preview_animation: that.preview_animation.export(),
          })
        } else {
          app.apperror(json);
        }
      }
    })
  },
  coomodityTAP: function (e) {
    wx.redirectTo(
      {
        url: '/pages/index/detail/index?id=' + e.currentTarget.id,
        success: function (res) {
          clearTimeout(timer);
        }
      }
    )
  },

  onShareAppMessage: function (res) {
    var that = this;
    return {
      title: that.data.data.name,
      path: 'pages/index/detail/index?id=' + that.data.data.id + '&regiment_share_userid=' + wx.getStorageSync('regiment_share_userid') + '&regiment_userid=' + wx.getStorageSync('regiment_userid'),
    }
  },
  toastChange: function () {
    this.setData({ toastHidden: true })
  },
  // 监听滚动事件
  scrollChange: function (e) {
    var that = this;
    if (e.detail.scrollTop > 400) {
      that.scrollTop_animation.translateY(-115).opacity(1).step();
    } else {
      that.scrollTop_animation.translateY(0).opacity(0).step();
    }
    that.setData({ scrollTop_animation: that.scrollTop_animation.export(), });


  },

  // 监听返回顶部
  scrollTop: function (e) {
    this.setData({
      toTop: 0,
      isScrollTop: true,
    });

  },

  /**
   * 获取优惠券列表
   * author: weiki
   */
  getCouponList: function () {
    var that = this;
    wx.request({
      url: app.url + '?controller=api_coupon&action=canReceive',
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },
      data: {
        goodsId: that.data.goods_id
      },
      success: function (res) {
        //新增优惠券之后，删除个人中心的优惠券缓存，以便生成最新数据
        wx.removeStorage({ key: 'valid', });
        wx.removeStorage({ key: 'expire', });

        for (var obj in res.data.result) {
          var reg = /([^\s]+)\s.*/;
          var str01 = getLocalTime(res.data.result[obj].start_time);
          var str02 = getLocalTime(res.data.result[obj].end_time);
          res.data.result[obj].start_time = str01//.replace(reg);
          res.data.result[obj].end_time = str02//.replace(reg);
          that.data.coupon.push(res.data.result[obj]);
        }
        function getLocalTime(nS) {
          var arr = new Date(parseInt(nS) * 1000).toLocaleString().substr(0, 10);
          var bbb = arr.split(" ");
          return bbb[0];
        }
        that.setData({
          coupon: that.data.coupon
        });
      },
    })
  }


})



/* 秒杀倒计时 */
function countdown(that) {
  var timestamp = Date.parse(new Date());
  timestamp = timestamp / 1000;
  var endTime = '';
  if (that.data.data.activity) {

    if (that.data.data.activity.start_time > timestamp) {
      endTime = that.data.data.activity.start_time;
    } else {
      endTime = that.data.data.activity.end_time;
    }

  } else if (that.data.data.promotion != '') {

    if (that.data.data.promotion.start_time > timestamp) {
      endTime = that.data.data.promotion.start_time;
    } else {
      endTime = that.data.data.promotion.end_time;
    }

  }
  var second = endTime - timestamp;

  var day = parseInt(second / 86400);
  if (('' + day).length == 1) {
    day = '0' + day;
  }
  var hour = parseInt(second % 86400 / 3600);
  if (('' + hour).length == 1) {
    hour = '0' + hour;
  }
  var minute = parseInt(second % 3600 / 60);
  if (('' + minute).length == 1) {
    minute = '0' + minute;
  }
  var second2 = parseInt(second % 3600 % 60 % 60);
  if (('' + second2).length == 1) {
    second2 = '0' + second2;
  }

  if (second < 0) {
    clearTimeout(timer);
    that.setData({
      "data.activity.end_time": "",
      timestamp: timestamp,
    });
    return;
  }

  timer = setTimeout(function () {

    that.setData({
      day: day,
      hour: hour,
      minute: minute,
      second: second2,
      timestamp: timestamp,
    });
    countdown(that);
  }
    , 1000)
}

// 动画方法
function moveAnimation(that) {

  var animation = wx.createAnimation({
    duration: 2000,
    timingFunction: 'ease-in-out',
  })

  var h = "auto";
  animation.height(h).translateY(-h).step();
  that.setData({
    animationData: animation.export()
  })
}


function imageForeach(photo, num) {
  var img = photo;
  var url = app.urlimg;
  var imgs = new Array;
  var i = 0;
  if (img[0] != undefined) {
    img.forEach(function (e) {
      if (i < num) {
        var imgurl = url + e;
        imgs.push(imgurl);
        i++;
      }
    })
  }
  return { 'imgurl': imgs, 'goods_thumb': imgs[0] }
}

// 图片数组重构
/*function imageForeach2(that) {
  var img = that.data.data.photo;
  var url = app.urlimg;
  var imgs = new Array;
  img.forEach(function (e) {
    var imgurl = url + e;
    imgs.push(imgurl);
  })
  that.setData({
    imgurl: imgs,
    goods_thumb: imgs[0],
  })

}*/